<template>
  <div class="image-upload-wrapper">
    <a-upload
        :name="uploadName"
        :action="uploadUrl"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :remove="handleRemove"
        :limit="1"
        :accept="acceptFileType"
        :show-upload-list="false"
        :custom-request="customUploadRequest"
    >
      <a-button type="primary" :disabled="isUploading">
        {{ isUploading? '上传中...' : '点击上传图片' }}
      </a-button>
    </a-upload>
    <div v-if="imageUrl" class="image-preview">
      <img :src="imageUrl" alt="预览图片" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import type { UploadFile } from 'ant-design-vue';
import { message } from 'ant-design-vue';

// 上传接口地址，需替换为实际后端接口
const uploadUrl = '/api/upload';
const uploadName = 'file';
const acceptFileType = 'image/*';

const fileList = ref<UploadFile[]>([]);
const imageUrl = ref<string | null>(null);
const isUploading = ref<boolean>(false);

// 上传前校验
const beforeUpload = (file: UploadFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPEG、PNG 图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB');
    return false;
  }
  return true;
};

// 处理文件移除
const handleRemove = (file: UploadFile) => {
  fileList.value = [];
  imageUrl.value = null;
};

// 自定义上传请求，用于处理上传进度等（示例中简单处理）
const customUploadRequest = (
    option: any
) => {
  isUploading.value = true;
  const formData = new FormData();
  formData.append(uploadName, option.file);
  // 这里使用fetch模拟上传请求，实际需替换为axios等库并结合后端接口
  fetch(uploadUrl, {
    method: 'POST',
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        isUploading.value = false;
        if (data.success) {
          fileList.value = [option.file];
          imageUrl.value = data.imageUrl;
          message.success('上传成功');
        } else {
          message.error('上传失败');
        }
      })
      .catch((error) => {
        isUploading.value = false;
        message.error('上传出错：' + error.message);
      });
};

onMounted(() => {
  // 这里可以在组件挂载时进行一些初始化操作，如从本地存储获取之前上传的图片信息等，
  // 若有需求可进一步完善
});
</script>

<style scoped>
.image-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-preview {
  margin-top: 10px;
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
}
</style>